<?php

namespace app\erp\controller;

use app\erp\model\Baojiadb;
use app\erp\model\Goodsdb;
use app\erp\model\GoodsPriceLogdb;
use app\erp\model\SalePricedb;
use app\erp\model\UGoodsdb;
use think\Db;

class Baojia extends Base
{
    protected $cols = array(
        array(
            'field' => 'baojia_id',
            'width' => 40,
            'title' => 'ID',
            'type' => 'checkbox',
            'fixed' => 'left'
        ),
        array(
            'field' => 'baojia_id',
            'width' => 50,
            'title' => 'ID',
            'fixed' => 'left',
            'hide' => 'true'
        ),
        array(
            'field' => 'apply_member_id',
            'width' => 120,
            'title' => '供应商',
            'templet' => '#apply_member_idTpl'
        ),
        array(
            'field' => 'create_time',
            'width' => 120,
            'title' => '报价时间'
        ),
        array(
            'field' => 'goods_shuzi',
            'width' => 160,
            'title' => '数字编码'
        ),
        array(
            'field' => 'goods_name',
            'width' => 300,
            'title' => '商品名称'
        ),
        array(
            'field' => 'audit_time',
            'width' => 120,
            'title' => '审核时间'
        ),
        array(
            'field' => 'lilv',
            'width' => 120,
            'title' => '利润率'
        ),
        array(
            'field' => 'chengben',
            'width' => 120,
            'title' => '供应商成本'
        ),
        array(
            'field' => 'baojia',
            'width' => 120,
            'title' => '报价',
            'edit' => true
        ),
        array(
            'field' => 'lilv',
            'width' => 120,
            'title' => '折扣率'
        ),
        array(
            'field' => 'cankao',
            'width' => 120,
            'title' => '参考价'
        ),
        array(
            'field' => 'zhouqi',
            'width' => 120,
            'title' => '报价期限'
        ),
        array(
            'field' => 'audit_state',
            'width' => 120,
            'title' => '审核状态',
            'templet' => '#audit_stateTpl'
        ),
        array(
            'field' => 'caigoujia',
            'width' => 120,
            'title' => '厂家成本'
        ),
        array(
            'field' => 'beizhu2',
            'width' => 120,
            'title' => '运营备注2'
        ),
        array(
            'field' => 'remark',
            'width' => 160,
            'title' => '拒绝原因'
        ),
        array(
            'field' => 'audit_member_id',
            'width' => 120,
            'title' => '审核人',
            'templet' => '#audit_member_idTpl'
        ),
        
        array(
            'field' => 'goods_sku',
            'width' => 160,
            'title' => '字母编码'
        ),
        array(
            'field' => 'goods_type',
            'width' => 120,
            'title' => '产品类型'
        ),
        array(
            'field' => 'kucun',
            'width' => 120,
            'title' => '库存',
            'hide' => 'true'
        ),
        array(
            'field' => 'zhenshi',
            'width' => 120,
            'title' => '真实库存',
            'edit' => true
        ),
        array(
            'field' => 'beizhu',
            'width' => 160,
            'title' => '供应商业务员'
        ),
        array(
            'field' => 'beizhu1',
            'width' => 160,
            'title' => '运营备注1',
            'hide' => 'true'
        ),
        array(
            'fixed' => 'right',
            'width' => 80,
            'title' => '操作',
            'toolbar' => '#baojia_tool'
        )
    );
    public $param = array();

    public function _initialize()
    {
        parent::_initialize();
        $request = request();
        $param = $request->param();
        $this->param = $param;
    }

    public function index()
    {
        /**
         * //$member_ids = [193,194];
         * $member_ids = [193];
         * if (!in_array(MEMBER_ID, $member_ids)) {
         * // 用户不属于上面用户组里面的数据 隐藏掉指定字段
         * $cols_array = ['chengben', 'baojia'];
         * foreach ($this->cols as $key => $val) {
         * if (isset($val['field']) && in_array($val['field'], $cols_array)) {
         * unset($this->cols[$key]);
         * }
         * }
         * }
         **/
        $this->assign('cols', json_encode($this->cols));
        return $this->fetch();
    }

    public function ajaxList()
    {
        $baojiadb = new Baojiadb();
        $baojiadb->param = $this->param;
        $get_baojia_count = $baojiadb->count();
        $get_baojia = $baojiadb->with(['users', 'admins'])->order('baojia_id desc')->page($this->param['page'], $this->param['limit'])->select();
        $this->layuiReturn($get_baojia, $get_baojia_count);
    }

    /**
     * Title("批量审核通过")
     */
    public function allPass(){
        $baojiadb = new Baojiadb();
        $get_baojia = $baojiadb->whereIn('baojia_id',$this->param['baojia_id_arr'])->select();
        foreach ($get_baojia as $key=>$val){
            $save_data['audit_state'] = 1;
            $save_data['audit_time'] = time();
            $save_data['audit_member_id'] = MEMBER_ID;
            $val->save($save_data);

            // 推送报价单
            $junapi = new \app\jun\controller\Api();
            if ($val['goods_type'] == '重点库') {
                $post_jun['priceList'] = array();
                $price_list_arr['sku'] = $val['goods_sku'];
                $price_list_arr['stock'] = $val['kucun'];
                $price_list_arr['price'] = $val['baojia'];

                $price_list_arr['linkurl'] = 'http://tailongjipc.dixintong.com/goods_detail.html?goods_sku=' . $val['goods_id'];
                $price_list_arr['eccode'] = $val['goods_id'];
                $price_list_arr['linkprice'] = $val['baojia'];
                array_push($post_jun['priceList'], $price_list_arr);
                $result = $junapi->ajaxCountPrice($post_jun);

                // 商品价格日志开始
                $goods_log_data = [];
                $goods_log_data['goods_sku'] = $val['goods_sku'];
                $goods_log_data['date'] = date('Y-m-d H:i:s');
                $goods_log_data['types'] = '报价审核';
                $temp_son = [];
                $temp_son['供应商名称'] = Db::name('member')->where('member_id', $val['apply_member_id'])->value('supplier_name');
                $temp_son['审核人'] = Db::name('member')->where('member_id', MEMBER_ID)->value('username');
                $temp_son['参考价'] = $val['cankao'];
                $temp_son['报价'] = $val['baojia'];
                $temp_son['最低价'] = Db::name('sale_price')->where('goods_sku', $val['goods_sku'])->value('zuidijia');
                $temp_son['成本'] = $val['chengben'];
                $temp_son['结束周期'] = $val['zhouqi'];
                $temp_son['业务员'] = $val['beizhu'];
                $temp_son['真实库存'] = $val['zhenshi'];
                $temp_son['库存'] = $val['kucun'];
                $temp_son['结果'] = $result['priceList'][0]['reason'];
                $goods_log_data['params'] = json_encode($temp_son, JSON_UNESCAPED_UNICODE);
                $goodsPriceLogdb = new GoodsPriceLogdb();
                $goodsPriceLogdb->save($goods_log_data);
                // 商品价格日志结束
            } else {
                $data = array();
                $temp ['sku'] = $val['goods_sku'];
                $temp ['updateType'] = 6;
                array_push($data, $temp);
                $junapi->ajaxproductupdateinfo($data);
            }

            // 同步商品价格
            $salepricedb = new SalePricedb();
            $get_sale = $salepricedb->where('site_id', SITE_ID)->where('goods_sku', $val['goods_sku'])->find();
            $get_sale->save(['api_price' => $val['baojia'], 'view_stock' => $val['kucun']]);
            // 同步商品表的库存
            $goodsdb = new Goodsdb();
            $get_goods = $goodsdb->where('goods_sku', $val['goods_sku'])->find();
            $get_goods->save(['view_stock' => $val['kucun']]);
            // 同步分系统
            $uGoodsdb = new UGoodsdb();
            $uGoodsdb->chkGoods($val['goods_id']);
        }

        $this->layuiReturn('success',1,'操作成功',1);
    }

    /**
     * Title("审核通过")
     */
    public function pass()
    {
        $baojiadb = new Baojiadb();
        $get_baojia = $baojiadb->find($this->param['baojia_id']);
        $save_data['audit_state'] = 1;
        $save_data['audit_time'] = time();
        $save_data['audit_member_id'] = MEMBER_ID;
        $get_baojia->save($save_data);
        // 推送报价单
        $junapi = new \app\jun\controller\Api();
        if ($get_baojia['goods_type'] == '重点库') {
            $post_jun['priceList'] = array();
            $price_list_arr['sku'] = $get_baojia['goods_sku'];
            $price_list_arr['stock'] = $get_baojia['kucun'];
            $price_list_arr['price'] = $get_baojia['baojia'];

            $price_list_arr['linkurl'] = 'http://tailongjipc.dixintong.com/goods_detail.html?goods_sku=' . $get_baojia['goods_id'];
            $price_list_arr['eccode'] = $get_baojia['goods_id'];
            $price_list_arr['linkprice'] = $get_baojia['baojia'];
            array_push($post_jun['priceList'], $price_list_arr);
            $result = $junapi->ajaxCountPrice($post_jun);

            // 商品价格日志开始
            $goods_log_data = [];
            $goods_log_data['goods_sku'] = $get_baojia['goods_sku'];
            $goods_log_data['date'] = date('Y-m-d H:i:s');
            $goods_log_data['types'] = '报价审核';
            $temp_son = [];
            $temp_son['供应商名称'] = Db::name('member')->where('member_id', $get_baojia['apply_member_id'])->value('supplier_name');
            $temp_son['审核人'] = Db::name('member')->where('member_id', MEMBER_ID)->value('username');
            $temp_son['参考价'] = $get_baojia['cankao'];
            $temp_son['报价'] = $get_baojia['baojia'];
            $temp_son['最低价'] = Db::name('sale_price')->where('goods_sku', $get_baojia['goods_sku'])->value('zuidijia');
            $temp_son['成本'] = $get_baojia['chengben'];
            $temp_son['结束周期'] = $get_baojia['zhouqi'];
            $temp_son['业务员'] = $get_baojia['beizhu'];
            $temp_son['真实库存'] = $get_baojia['zhenshi'];
            $temp_son['库存'] = $get_baojia['kucun'];
            $temp_son['结果'] = $result['priceList'][0]['reason'];
            $goods_log_data['params'] = json_encode($temp_son, JSON_UNESCAPED_UNICODE);
            $goodsPriceLogdb = new GoodsPriceLogdb();
            $goodsPriceLogdb->save($goods_log_data);
            // 商品价格日志结束
        } else {
            $data = array();
            $temp ['sku'] = $get_baojia['goods_sku'];
            $temp ['updateType'] = 6;
            array_push($data, $temp);
            $junapi->ajaxproductupdateinfo($data);
        }
        // 同步商品价格
        $salepricedb = new SalePricedb();
        $get_sale = $salepricedb->where('site_id', SITE_ID)->where('goods_sku', $get_baojia['goods_sku'])->find();
        $get_sale->save(['api_price' => $get_baojia['baojia'], 'view_stock' => $get_baojia['kucun']]);
        // 同步商品表的库存
        $goodsdb = new Goodsdb();
        $get_goods = $goodsdb->where('site_id', SITE_ID)->where('goods_sku', $get_baojia['goods_sku'])->find();
        $get_goods->save(['view_stock' => $get_baojia['kucun']]);
        // 同步分系统
        $uGoodsdb = new UGoodsdb();
        $uGoodsdb->chkGoods($get_baojia['goods_id']);
        $this->layuiReturn('success');
    }

    /**
     * Title("批量驳回申请")
     */
    public function allRefuse(){
        $baojiadb = new Baojiadb();
        $get_baojia = $baojiadb->whereIn('baojia_id',$this->param['baojia_id_arr'])->select();
        foreach ($get_baojia as $key=>$val){
            $save_data['audit_state'] = 3;
            $save_data['audit_time'] = time();
            $save_data['audit_member_id'] = MEMBER_ID;
            $save_data['remark'] = $this->param['remark'];
            $val->save($save_data);
        }

        $this->layuiReturn('success',1,'操作成功',1);
    }

    /**
     * Title("驳回申请")
     */
    public function refuse()
    {
        $baojiadb = new Baojiadb();
        $get_baojia = $baojiadb->find($this->param['baojia_id']);
        $save_data['audit_state'] = 3;
        $save_data['audit_time'] = time();
        $save_data['audit_member_id'] = MEMBER_ID;
        $save_data['remark'] = $this->param['remark'];
        $get_baojia->save($save_data);
        $this->layuiReturn('success');
    }

    public function edit()
    {
        $baojiadb = new Baojiadb();
        $get_baojia = $baojiadb->find($this->param['baojia_id']);
        if ($get_baojia) {
            $get_baojia->save(['zhenshi' => $this->param['value']]);
            $goodsdb = new Goodsdb();
            $get_goods = $goodsdb->where('goods_id', $get_baojia['goods_id'])->find();
            if ($get_goods) {
                $get_goods->save(['zhenshi' => $this->param['value']]);
            }
        }
        $this->success('报价成功');
    }

    public function saveData()
    {
        $this->db->param = $this->post;
        $return = $this->db->ajaxSave();
        if ($return != 'success') {
            $this->layuiReturn($return, 0, $return, -1);
        } else {
            $this->layuiReturn('保存成功');
        }
    }

    public function export()
    {
        ini_set('memory_limit', '4096M');
        $baojiadb = new Baojiadb();
        $baojiadb->param = $this->param;
        $get_baojia = $baojiadb->with(['users', 'admins'])->order('baojia_id desc')->select();
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        ob_end_clean();
        $excel_name = '报价商品' . date('Ymdhi') . '.' . rand(1000, 9999) . '.xls';
        $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
        $obj_act_sheet = $phpExcel->getActiveSheet();
        $i = 1;
        $header_data = array(
            '产品类型',
            '供应商',
            '报价时间',
            '字母编码',
            '数字编码',
            '商品名称',
            '利润率',
            '审核时间',
            '供应商成本价',
            '参考价',
            '报价',
            '真实库存',
            '厂家成本',
            '审核状态',
            '拒绝原因',
            '审核人',
            //  '运营备注1',
            '运营备注2',
            '报价期限',
            '供应商业务员'
        );
        $this->setExcelHeader($obj_act_sheet, $phpExcel, $header_data);
        $excel_data = array();
        $audit_state_arr = array(
            '1' => '审核通过',
            '2' => '等待审核',
            '3' => '驳回审核'
        );
        foreach ($get_baojia as $key => $val) {
            unset ($temp);
            $temp [0] = $val ['goods_type'];
            $temp [1] = $val ['users']['supplier_name'];
            $temp [2] = $val ['create_time'];
            $temp [3] = $val ['goods_sku'];
            $temp [4] = $val ['goods_shuzi'];
            $temp [5] = $val ['goods_name'];
            $temp [6] = $val ['lilv'];
            $temp [7] = $val ['audit_time'];
            $temp [8] = $val ['chengben'];
            $temp [9] = $val ['cankao'];
            $temp [10] = $val ['baojia'];
            $temp [11] = $val ['zhenshi'];
            $temp [12] = $val ['caigoujia'];
            $temp [13] = $audit_state_arr[$val ['audit_state']];
            $temp [14] = $val ['remark'];
            $temp [15] = $val ['admins']['realname'];
            //  $temp [16] = $val ['beizhu1'];
            $temp [16] = $val ['beizhu2'];
            $temp [17] = $val['zhouqi'];
            $temp [18] = $val['beizhu'];

            array_push($excel_data, $temp);
        }
        $vAlign = new \PHPExcel_Style_Alignment ();
        $this->setExcelBody($obj_act_sheet, $phpExcel, $excel_data, count($header_data), $vAlign::VERTICAL_CENTER);

        $obj_write->save('./uploads/Excel/' . $excel_name);
        $all_path = $excel_name;
        $this->layuiReturn(url('Order/downExcel', array(
            'excel_name' => $all_path
        )), 1, '导出成功', 1);
    }

    protected function setExcelHeader($obj_act_sheet, $phpExcel, $data)
    {
        $start = 65;
        for ($i = 0; $i < count($data); $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26)) . '1';
                $cell_name = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i) . '1';
                $cell_name = chr($start + $i);
            }
            $obj_act_sheet->setCellValue($cell_value, $data [$i]);
            $phpExcel->getActiveSheet()->getColumnDimension($cell_name)->setWidth(20);
        }
    }

    protected function setExcelBody($obj_act_sheet, $phpExcel, $data, $count, $valign)
    {
        $start = 65;
        for ($i = 0; $i < $count; $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i);
            }
            $j = 2;
            $end_merge = 2;
            foreach ($data as $key => $val) {
                $obj_act_sheet->setCellValue($cell_value . $j, str_replace('_diff', '', str_replace('_add', '', $val [$i])));
                // 合并单元格
                $phpExcel->getActiveSheet()->getStyle($cell_value . $j)->getAlignment()->setVertical($valign);
                $j++;
            }
        }
        // 合并单元格
        $temp = '';
        $ceil_num = 0;
        $start_num = 2; // 第二行是正本数据
        if ($ceil_num > 1) {
            for ($y = 0; $y < 33; $y++) {
                $cell_value = chr($start + $y);
                if ($y >= 26) {
                    $cell_value = 'A' . chr($start + $y - 26);
                }
                $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
            }
        }
    }

}